package com.LachesismStorm.lachesism.member.service.impl;

import com.LachesismStorm.lachesism.core.exception.Asserts;
import com.LachesismStorm.lachesism.member.service.WMJService;
import com.LachesismStorm.lachesism.member.vo.CertQueryVO;
import com.LachesismStorm.lachesism.member.vo.CertVO;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.ConvolveOp;
import java.awt.image.Kernel;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

import static com.LachesismStorm.lachesism.core.util.LachesismTools.getTime;
import static com.LachesismStorm.lachesism.member.util.certUtil.*;

/**
 * @Author lachesism
 * @Date 2024-12-29 19:38
 **/
@Service
public class WMJServiceImpl implements WMJService {
    @SneakyThrows
    @Override
    public String getSixtyCert(String name, Integer xLocation) {
        // 读取图片
        BufferedImage image = ImageIO.read(new File("/project/media/file/tempPic/60.png"));

        // 获取图片的Graphics对象
        Graphics2D g2d = image.createGraphics();

        // 开启抗锯齿
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        Font font = Font.createFont(Font.TRUETYPE_FONT, new File("/project/media/font/SongtiSCRegular.ttf"));
        font = font.deriveFont(Font.BOLD, 25);  // 设置字体大小
        g2d.setFont(font);
        // 设置字体、颜色等
        g2d.setColor(Color.decode("#45564e"));  // 设置文字颜色为 #45564e

        // 绘制文本
        g2d.drawString(name, xLocation, 190);
        g2d.dispose();

        // 应用高斯模糊
        BufferedImage blurredImage = applyGaussianBlur(image);
        String time = getTime("MMddHHmmSS");
        // 保存修改后的图片
        ImageIO.write(blurredImage, "png", new File("/project/media/temp/" + time + name + ".png"));
        return "https://www.yunox.cn/temp/" + time + name + ".png";
    }

    @SneakyThrows
    @Override
    public String getESixtyCert(CertVO certVO) {
        // 读取图片
        BufferedImage image = ImageIO.read(new File("/project/media/file/tempPic/e60.png"));
        // 获取图片的Graphics对象
        Graphics2D g2d = image.createGraphics();
        // 设置字体、颜色等
        g2d.setColor(Color.decode("#45564e"));  // 设置文字颜色为 #45564e
        // 创建一个新的BufferedImage来绘制文本
        BufferedImage textLayer = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2dText = textLayer.createGraphics();
        // 开启抗锯齿
        g2dText.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        Font font = Font.createFont(Font.TRUETYPE_FONT, new File("/project/media/font/SongtiSCRegular.ttf"));
        font = font.deriveFont(Font.BOLD, 77);  // 设置字体大小
        g2dText.setFont(font);
        g2dText.setColor(Color.decode("#364741"));  // 设置文字颜色为 #364741
        g2dText.drawString(certVO.getUserName(), certVO.getUserNameXLocation(), certVO.getUserNameYLocation());
        g2dText.drawString(certVO.getGender(), certVO.getGenderXLocation(), certVO.getGenderYLocation());
        g2dText.drawString(certVO.getBirthDate(), certVO.getBirthDateXLocation(), certVO.getBirthDateYLocation());
        g2dText.drawString(certVO.getCardId(), certVO.getCardIdXLocation(), certVO.getCardIdYLocation());
        g2dText.drawString(certVO.getCertName(), certVO.getCertNameXLocation(), certVO.getCertNameYLocation());
        g2dText.drawString(certVO.getLevel(), certVO.getLevelXLocation(), certVO.getLevelYLocation());
        g2dText.drawString(certVO.getCertNo(), certVO.getCertNoXLocation(), certVO.getCertNoYLocation());
        g2dText.drawString(certVO.getYear(), certVO.getYearXLocation(), certVO.getYearYLocation());
        g2dText.drawString(certVO.getMonth(), certVO.getMonthXLocation(), certVO.getMonthYLocation());
        g2dText.drawString(certVO.getDay(), certVO.getDayXLocation(), certVO.getDayYLocation());
        g2dText.dispose();
        // 对文本层应用高斯模糊
        BufferedImage blurredTextLayer = applyGaussianBlur(textLayer);
        // 将模糊后的文本层绘制到原图像上
        g2d.drawImage(blurredTextLayer, 0, 0, null);
        // 读取要添加的图片（无需调整大小）
        BufferedImage overlayImage = ImageIO.read(new File(certVO.getPicPath()));
        // 你可以根据需要调整图片的绘制位置，当前是放置在(100, 100)位置
        g2d.drawImage(overlayImage, 166, 160, null);
        // 将图片直接绘制到原图上
        g2d.dispose();

        // 进行图片缩放：将图片缩放到原图的 33.3%
        int scaledWidth = (int) (image.getWidth() * 0.333);  // 缩放后的宽度
        int scaledHeight = (int) (image.getHeight() * 0.333);  // 缩放后的高度
        Image scaledImage = image.getScaledInstance(scaledWidth, scaledHeight, Image.SCALE_SMOOTH);

        // 创建一个新的BufferedImage用于存放缩放后的图像
        BufferedImage scaledBufferedImage = new BufferedImage(scaledWidth, scaledHeight, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2dScaled = scaledBufferedImage.createGraphics();
        g2dScaled.drawImage(scaledImage, 0, 0, null);  // 绘制缩放后的图像
        g2dScaled.dispose();
        String time = getTime("MMddHHmmSS");
        // 保存修改后的图片
        ImageIO.write(scaledBufferedImage, "png", new File("/project/media/temp/" + certVO.getUserName() + time + ".png"));
        return "https://www.yunox.cn/temp/" + certVO.getUserName() + time + ".png";
    }

    @SneakyThrows
    @Override
    public String getESixtyCert2(CertVO certVO) {
        // 读取图片
        BufferedImage image = ImageIO.read(new File("/project/media/file/tempPic/e60.png"));
        // 获取图片的Graphics对象
        Graphics2D g2d = image.createGraphics();
        // 设置字体、颜色等
        g2d.setColor(Color.decode("#45564e"));  // 设置文字颜色为 #45564e
        // 创建一个新的BufferedImage来绘制文本
        BufferedImage textLayer = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2dText = textLayer.createGraphics();
        // 开启抗锯齿
        g2dText.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        Font font = Font.createFont(Font.TRUETYPE_FONT, new File("/project/media/font/SongtiSCRegular.ttf"));
        font = font.deriveFont(Font.BOLD, 77);  // 设置字体大小
        g2dText.setFont(font);
        g2dText.setColor(Color.decode("#364741"));  // 设置文字颜色为 #364741
        g2dText.drawString(certVO.getUserName(), certVO.getUserNameXLocation(), certVO.getUserNameYLocation());
        g2dText.drawString(certVO.getUserName2(), certVO.getUserName2XLocation(), certVO.getUserName2YLocation());
        g2dText.drawString(certVO.getGender(), certVO.getGenderXLocation(), certVO.getGenderYLocation());
        g2dText.drawString(certVO.getBirthDate(), certVO.getBirthDateXLocation(), certVO.getBirthDateYLocation());
        g2dText.drawString(certVO.getCardId(), certVO.getCardIdXLocation(), certVO.getCardIdYLocation());
        g2dText.drawString(certVO.getCertName(), certVO.getCertNameXLocation(), certVO.getCertNameYLocation());
        g2dText.drawString(certVO.getCertName2(), certVO.getCertName2XLocation(), certVO.getCertName2YLocation());
        g2dText.drawString(certVO.getLevel(), certVO.getLevelXLocation(), certVO.getLevelYLocation());
        g2dText.drawString(certVO.getCertNo(), certVO.getCertNoXLocation(), certVO.getCertNoYLocation());
        g2dText.drawString(certVO.getYear(), certVO.getYearXLocation(), certVO.getYearYLocation());
        g2dText.drawString(certVO.getMonth(), certVO.getMonthXLocation(), certVO.getMonthYLocation());
        g2dText.drawString(certVO.getDay(), certVO.getDayXLocation(), certVO.getDayYLocation());
        g2dText.dispose();
        // 对文本层应用高斯模糊
        BufferedImage blurredTextLayer = applyGaussianBlur(textLayer);
        // 将模糊后的文本层绘制到原图像上
        g2d.drawImage(blurredTextLayer, 0, 0, null);
        // 读取要添加的图片（无需调整大小）
        BufferedImage overlayImage = ImageIO.read(new File(certVO.getPicPath()));
        // 你可以根据需要调整图片的绘制位置，当前是放置在(100, 100)位置
        g2d.drawImage(overlayImage, 166, 160, null);
        // 将图片直接绘制到原图上
        g2d.dispose();

        // 进行图片缩放：将图片缩放到原图的 33.3%
        int scaledWidth = (int) (image.getWidth() * 0.333);  // 缩放后的宽度
        int scaledHeight = (int) (image.getHeight() * 0.333);  // 缩放后的高度
        Image scaledImage = image.getScaledInstance(scaledWidth, scaledHeight, Image.SCALE_SMOOTH);

        // 创建一个新的BufferedImage用于存放缩放后的图像
        BufferedImage scaledBufferedImage = new BufferedImage(scaledWidth, scaledHeight, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2dScaled = scaledBufferedImage.createGraphics();
        g2dScaled.drawImage(scaledImage, 0, 0, null);  // 绘制缩放后的图像
        g2dScaled.dispose();
        String time = getTime("MMddHHmmSS");
        // 保存修改后的图片
        ImageIO.write(scaledBufferedImage, "png", new File("/project/media/temp/" + certVO.getUserName() + certVO.getUserName2()+ time + ".png"));
        return "https://www.yunox.cn/temp/" + certVO.getUserName() + certVO.getUserName2() + time + ".png";

    }


    @SneakyThrows
    @Override
    public String getHundredCert(String name, Integer xLocation) {
        // 读取图片
        BufferedImage image = ImageIO.read(new File("/project/media/file/tempPic/100.png"));

        // 获取图片的Graphics对象
        Graphics2D g2d = image.createGraphics();

        // 开启抗锯齿
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        Font font = Font.createFont(Font.TRUETYPE_FONT, new File("/project/media/font/SongtiSCRegular.ttf"));
        font = font.deriveFont(Font.BOLD, 16);  // 设置字体大小
        g2d.setFont(font);
        // 设置字体、颜色等
        g2d.setColor(Color.decode("#45564e"));  // 设置文字颜色为 #45564e

        // 绘制文本
        g2d.drawString(name, xLocation, 166);
        g2d.dispose();

        // 应用高斯模糊
        BufferedImage blurredImage = applyGaussianBlur(image);
        String time = getTime("MMddHHmmSS");
        // 保存修改后的图片
        ImageIO.write(blurredImage, "png", new File("/project/media/temp/" + time + name + ".png"));
        return "https://www.yunox.cn/temp/" + time + name + ".png";
    }

    @Override
    @SneakyThrows
    public String getEHundredCert(CertVO certVO) {
// 读取图片
        BufferedImage image = ImageIO.read(new File("/project/media/file/tempPic/r100.png"));
//        BufferedImage image = ImageIO.read(new File("/Users/yuno/Downloads/r100.png"));
        // 获取图片的Graphics对象
        Graphics2D g2d = image.createGraphics();
        // 设置字体、颜色等
        // 创建一个新的BufferedImage来绘制文本
        BufferedImage textLayer = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2dText = textLayer.createGraphics();
        // 开启抗锯齿
        g2dText.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
//        Font font = new Font("SANS_SERIF", Font.PLAIN, 45);  // 默认字体系列 + 字体大小
//        g2dText.setFont(font);
        Font font = Font.createFont(Font.TRUETYPE_FONT, new File("/project/media/font/simsun.ttc"));
        font = font.deriveFont(Font.PLAIN, 48);  // 设置字体大小
//        font.deriveFont(Font.PLAIN,30);
        g2dText.setFont(font);
        g2dText.setColor(Color.decode("#000400"));  // 设置文字颜色为 #364741
        g2dText.drawString(certVO.getUserName(), certVO.getUserNameXLocation(), certVO.getUserNameYLocation());//姓名
        g2dText.drawString(certVO.getGender(), certVO.getGenderXLocation(), certVO.getGenderYLocation());//姓名
        g2dText.drawString(certVO.getCardId(), certVO.getCardIdXLocation(), certVO.getCardIdYLocation());//身份证号
        g2dText.drawString(certVO.getCertName(), certVO.getCertNameXLocation(), certVO.getCertNameYLocation());//专业名词
        g2dText.drawString(certVO.getLevel(), certVO.getLevelXLocation(), certVO.getLevelYLocation());//技能等级
        g2dText.drawString(certVO.getCertNo(), certVO.getCertNoXLocation(), certVO.getCertNoYLocation());//证书编号
        g2dText.drawString(certVO.getYear(), certVO.getYearXLocation(), certVO.getYearYLocation());
        g2dText.drawString(certVO.getBirthDate(), certVO.getBirthDateXLocation(), certVO.getBirthDateYLocation());
        g2dText.drawString(certVO.getTheoryScore(), certVO.getTheoryScoreXLocation(), certVO.getTheoryScoreYLocation());
        g2dText.drawString(certVO.getAssessScore(), certVO.getAssessScoreXLocation(), certVO.getAssessScoreYLocation());
        font = font.deriveFont(Font.PLAIN, 35);  // 设置字体大小
        g2dText.setFont(font);
        g2dText.drawString(certVO.getWorkAddress(), certVO.getWorkAddressXLocation(), certVO.getWorkAddressYLocation());

        g2dText.dispose();
        // 将模糊后的文本层绘制到原图像上
        g2d.drawImage(textLayer, 0, 0, null);
        // 读取要添加的图片（无需调整大小）
        BufferedImage overlayImage = ImageIO.read(new File(certVO.getPicPath()));
        // 你可以根据需要调整图片的绘制位置，当前是放置在(100, 100)位置
        g2d.drawImage(overlayImage, 256, 178, null);
        // 读取要添加的二维码（无需调整大小）
        BufferedImage qrCodeImage = generateQRCode(618, certVO.getQrCodeInfo()); // 假设用证书编号生成二维码
        // 你可以根据需要调整图片的绘制位置，当前是放置在(100, 100)位置
        g2d.drawImage(qrCodeImage, 642, 262, null);
//        g2d.drawImage(overlayImage, 920, 455, null);
        // 将图片直接绘制到原图上
        g2d.dispose();
        String time = getTime("MMddHHmmSS");
        // 保存修改后的图片
//        ImageIO.write(image, "png", new File("/project/media/temp/" + certVO.getUserName() + time + ".png"));
        ImageIO.write(image, "png", new File("/project/media/temp/" + certVO.getUserName() + time + ".png"));
        return "https://www.yunox.cn/temp/" + certVO.getUserName() + time + ".png";
    }

    @Override
    @SneakyThrows
    public String getHundredFiftyCert(String name, Integer xLocation) {
        // 读取图片
        BufferedImage image = ImageIO.read(new File("/project/media/file/tempPic/r150.png"));
//        BufferedImage image = ImageIO.read(new File("/Users/yuno/Downloads/r150.png"));

        // 获取图片的Graphics对象
        Graphics2D g2d = image.createGraphics();

        // 开启抗锯齿
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        Font font = Font.createFont(Font.TRUETYPE_FONT, new File("/project/media/font/kai2.ttf"));
//        Font font = Font.createFont(Font.TRUETYPE_FONT, new File("/Users/yuno/Downloads/kai2.ttf"));
        font = font.deriveFont(Font.PLAIN, 18);  // 设置字体大小
        g2d.setFont(font);
        // 设置字体、颜色等
        g2d.setColor(Color.decode("#45564e"));  // 设置文字颜色为 #45564e
        // 绘制文本
        g2d.drawString(name, xLocation, 1370);
        g2d.dispose();
        // 应用高斯模糊
        BufferedImage blurredImage = applyGaussianBlur(image);
        String time = getTime("MMddHHmmSS");
        // 保存修改后的图片
        ImageIO.write(blurredImage, "png", new File("/project/media/temp/" + time + name + ".png"));
//        ImageIO.write(blurredImage, "png", new File("/Users/yuno/Downloads/" + time + name + ".png"));
        return "https://www.yunox.cn/temp/" + time + name + ".png";
    }

    @Override
    @SneakyThrows
    public String edit100PicSize(MultipartFile file) {
        String orgFileName = file.getOriginalFilename();
        // 获取文件扩展名
        String fileExtend = orgFileName.substring(orgFileName.lastIndexOf(".") + 1).toLowerCase();

        // 生成唯一的文件名（防止文件名重复），统一保存为 PNG 格式
        String uniqueFileName = getTime("MMddHHmmSS") + ".png";

        // 指定保存路径
        String saveDir = "/project/media/temp/";
//        String saveDir = "/Users/yuno/Downloads/";
        // 创建文件目录（如果目录不存在，则创建）
        Path path = Paths.get(saveDir);
        if (!Files.exists(path)) {
            Files.createDirectories(path);  // 创建多级目录
        }
        // 创建目标文件路径
        File targetFile = new File(saveDir + uniqueFileName);
        // 首先尝试将文件转换成图片
        BufferedImage image = ImageIO.read(file.getInputStream());
        // 创建一个新的BufferedImage，指定目标大小
        BufferedImage resizedImage = new BufferedImage(281, 397, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = resizedImage.createGraphics();
        g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g2d.drawImage(image, 0, 0, 281, 397, null);
        g2d.dispose();  // 释放资源

        // 保存调整大小后的图片
        ImageIO.write(resizedImage, "PNG", targetFile);  // 使用 PNG 格式保存

        // 返回文件的绝对路径
        return targetFile.getAbsolutePath();
    }


    @Override
    @SneakyThrows
    public String getEHundredFiftyCert(CertVO certVO) {
        // 读取图片
        BufferedImage image = ImageIO.read(new File("/project/media/file/tempPic/150.png"));
        // 获取图片的Graphics对象
        Graphics2D g2d = image.createGraphics();
        // 设置字体、颜色等
        // 创建一个新的BufferedImage来绘制文本
        BufferedImage textLayer = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2dText = textLayer.createGraphics();
        // 开启抗锯齿
        g2dText.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        Font font = Font.createFont(Font.TRUETYPE_FONT, new File("/project/media/font/kai2.ttf"));
        font = font.deriveFont(Font.PLAIN, 30);  // 设置字体大小
        g2dText.setFont(font);
        g2dText.setColor(Color.decode("#000400"));  // 设置文字颜色为 #364741
        g2dText.drawString(certVO.getUserName(), certVO.getUserNameXLocation(), certVO.getUserNameYLocation());//姓名
        g2dText.drawString(certVO.getCardId(), certVO.getCardIdXLocation(), certVO.getCardIdYLocation());//身份证号
        g2dText.drawString(certVO.getCertName(), certVO.getCertNameXLocation(), certVO.getCertNameYLocation());//专业名词
        g2dText.drawString(certVO.getLevel(), certVO.getLevelXLocation(), certVO.getLevelYLocation());//技能等级
        g2dText.drawString(certVO.getCertNo(), certVO.getCertNoXLocation(), certVO.getCertNoYLocation());//证书编号
        g2dText.drawString(certVO.getYear(), certVO.getYearXLocation(), certVO.getYearYLocation());
        g2dText.drawString(certVO.getMonth(), certVO.getMonthXLocation(), certVO.getMonthYLocation());
        g2dText.drawString(certVO.getDay(), certVO.getDayXLocation(), certVO.getDayYLocation());
        g2dText.dispose();
        // 将模糊后的文本层绘制到原图像上
        g2d.drawImage(textLayer, 0, 0, null);
        // 读取要添加的图片（无需调整大小）
        BufferedImage overlayImage = ImageIO.read(new File(certVO.getPicPath()));
        // 你可以根据需要调整图片的绘制位置，当前是放置在(100, 100)位置
        g2d.drawImage(overlayImage, 915, 229, null);
        // 读取要添加的二维码（无需调整大小）
        BufferedImage qrCodeImage = generateQRCode(370, certVO.getQrCodeInfo()); // 假设用证书编号生成二维码
        // 你可以根据需要调整图片的绘制位置，当前是放置在(100, 100)位置
        g2d.drawImage(qrCodeImage, 1165, 252, null);
//        g2d.drawImage(overlayImage, 920, 455, null);
        // 将图片直接绘制到原图上
        g2d.dispose();
        String time = getTime("MMddHHmmSS");
        // 保存修改后的图片
        ImageIO.write(image, "png", new File("/project/media/temp/" + certVO.getUserName() + time + ".png"));
        return "https://www.yunox.cn/temp/" + certVO.getUserName() + time + ".png";
    }

    @Override
    @SneakyThrows
    public String edit150PicSize(MultipartFile file) {
        String orgFileName = file.getOriginalFilename();
        // 获取文件扩展名
        String fileExtend = orgFileName.substring(orgFileName.lastIndexOf(".") + 1).toLowerCase();

        // 生成唯一的文件名（防止文件名重复），统一保存为 PNG 格式
        String uniqueFileName = getTime("MMddHHmmSS") + ".png";

        // 指定保存路径
        String saveDir = "/project/media/temp/";
        // 创建文件目录（如果目录不存在，则创建）
        Path path = Paths.get(saveDir);
        if (!Files.exists(path)) {
            Files.createDirectories(path);  // 创建多级目录
        }
        // 创建目标文件路径
        File targetFile = new File(saveDir + uniqueFileName);
        // 首先尝试将文件转换成图片
        BufferedImage image = ImageIO.read(file.getInputStream());
        // 创建一个新的BufferedImage，指定目标大小
        BufferedImage resizedImage = new BufferedImage(168, 235, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = resizedImage.createGraphics();
        g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g2d.drawImage(image, 0, 0, 168, 235, null);
        g2d.dispose();  // 释放资源

        // 保存调整大小后的图片
        ImageIO.write(resizedImage, "PNG", targetFile);  // 使用 PNG 格式保存

        // 返回文件的绝对路径
        return targetFile.getAbsolutePath();
    }


    @SneakyThrows
    @Override
    public String uploadPic(MultipartFile file) {
        String orgFileName = file.getOriginalFilename();
        // 获取文件扩展名
        String fileExtend = orgFileName.substring(orgFileName.lastIndexOf(".") + 1).toLowerCase();

        // 生成唯一的文件名（防止文件名重复），统一保存为 PNG 格式
        String uniqueFileName = getTime("MMddHHmmSS") + ".png";

        // 指定保存路径
        String saveDir = "/project/media/temp/";
//        String saveDir = "/Users/yuno/Downloads/";

        // 创建文件目录（如果目录不存在，则创建）
        Path path = Paths.get(saveDir);
        if (!Files.exists(path)) {
            Files.createDirectories(path);  // 创建多级目录
        }
        // 创建目标文件路径
        File targetFile = new File(saveDir + uniqueFileName);
        // 首先尝试将文件转换成图片
        BufferedImage image = ImageIO.read(file.getInputStream());
        // 创建一个新的BufferedImage，指定目标大小
        BufferedImage resizedImage = new BufferedImage(524, 707, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = resizedImage.createGraphics();
        g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g2d.drawImage(image, 0, 0, 524, 707, null);
        g2d.dispose();  // 释放资源

        // 保存调整大小后的图片
        ImageIO.write(resizedImage, "PNG", targetFile);  // 使用 PNG 格式保存

        // 返回文件的绝对路径
        return targetFile.getAbsolutePath();
    }


    // 生成二维码的辅助方法
    public BufferedImage generateQRCode(Integer inputSize, String content) throws Exception {
        int size = inputSize; // 二维码尺寸
        Map<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        hints.put(EncodeHintType.MARGIN, 1); // 去掉二维码周围的空白区域
        // 使用ZXing生成二维码矩阵
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, size, size, hints);
        // 将BitMatrix转化为BufferedImage
        BufferedImage image = new BufferedImage(size, size, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < size; x++) {
            for (int y = 0; y < size; y++) {
                image.setRGB(x, y, bitMatrix.get(x, y) ? Color.BLACK.getRGB() : Color.WHITE.getRGB());
            }
        }
        // 缩小二维码图像为原始尺寸的 50%（0.5）
        int scaledWidth = (int) (size * 0.5);
        int scaledHeight = (int) (size * 0.5);
        // 创建一个新的 BufferedImage 来存放缩放后的二维码
        BufferedImage scaledImage = new BufferedImage(scaledWidth, scaledHeight, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = scaledImage.createGraphics();
        // 进行图像缩放
        g2d.drawImage(image, 0, 0, scaledWidth, scaledHeight, null);
        g2d.dispose();
        // 返回缩小后的二维码图像
        return scaledImage;
    }


    @Override
    public String getCookie() {
        return getCertCookie();
    }

    @Override
    public String getCaptcha(String cookie) {
        return "data:image/png;base64," + getCaptchaImage(cookie);
    }

    @Override
    public CertQueryVO queryCert(CertQueryVO certQueryVO) {
        try {
            String queryResult = queryCertificate(certQueryVO.getName(), certQueryVO.getCertNum(), certQueryVO.getIdCard(), certQueryVO.getCode(), certQueryVO.getCookie());
            System.out.println("queryResult:   " + queryResult);
            if (queryResult.contains("验证码不正确")) {
                Asserts.fail("验证码不正确哦");
            }
            if (queryResult.contains("证书不存在")) {
                Asserts.fail("证书不存在");
            }
            String data = extractDataFromJson(queryResult);
            String finalResult = formatContent(data, certQueryVO.getCookie());
            System.out.println("证书详情:    " + finalResult);
            CertQueryVO certQuery = new CertQueryVO();
            certQuery.setName(extractValue(finalResult, "<li>姓 &nbsp;&nbsp;名: (.*?)</li>"));
            certQuery.setIdCard(extractValue(finalResult, "<li>身份证号: (.*?)</li>"));
            certQuery.setCertName(extractValue(finalResult, "<li>专业名称: (.*?)</li>"));
            certQuery.setLevel(extractValue(finalResult, "<li>技能等级: (.*?)</li>"));
            certQuery.setCertNum(extractValue(finalResult, "<li>证书编号: (.*?)</li>"));
            certQuery.setCertDate(extractValue(finalResult, "<li>发证时间: (.*?)</li>"));
            certQuery.setImgUrl(extractValue(finalResult, "<ul id=\"my1\">                <img src=\"(.*?)\""));
            return certQuery;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    public static void main(String[] args) {
        String a = "{\"Data\":\"\\/zscx\\/41649.html\",\"Status\":1,\"Message\":\"成功\",\"Timestamp\":1735667626}";
        System.out.println(extractDataFromJson(a));
    }

    public BufferedImage applyGaussianBlur(BufferedImage image) {
        float[] matrix = {
                1f / 16f, 2f / 16f, 1f / 16f,
                2f / 16f, 4f / 16f, 2f / 16f,
                1f / 16f, 2f / 16f, 1f / 16f
        };
        Kernel kernel = new Kernel(3, 3, matrix);  // 使用 3x3 核心
        ConvolveOp convolveOp = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);
        return convolveOp.filter(image, null);  // 对图像应用模糊
    }

}
